package cn.edu.cqie.impl;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Optional;

import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;

import cn.edu.cqie.bo.AccountBo;
import cn.edu.cqie.dao.ProductDao;
import cn.edu.cqie.dao.SysImagesDao;
import cn.edu.cqie.entity.Product;
import cn.edu.cqie.entity.SysImages;
import cn.edu.cqie.enums.CheckStateEnum;
import cn.edu.cqie.enums.GameAccountHighlightsEnum;
import cn.edu.cqie.enums.GameAreaEnum;
import cn.edu.cqie.enums.GameBodyTypeEnum;
import cn.edu.cqie.enums.GameCampEnum;
import cn.edu.cqie.enums.GameEquipmentEnum;
import cn.edu.cqie.enums.GameSectEnum;
import cn.edu.cqie.enums.GameServerEnum;
import cn.edu.cqie.enums.RespToAppEnum;
import cn.edu.cqie.enums.StateEnum;
import cn.edu.cqie.service.AccountService;
import cn.edu.cqie.utils.BizException;
import cn.edu.cqie.utils.CommonConstant;

@Service
public class AccountImpl implements AccountService {

	private final static Logger logger = LoggerFactory.getLogger(AccountImpl.class);

	@Autowired
	private ProductDao productDao;

	@Autowired
	private SysImagesDao sysImagesDao;

	@Override
	public void load(AccountBo bo) {

		logger.info("AccountImpl-load-service-in,{}", JSONObject.toJSONString(bo));

		// 1加载大区
		bo.setGameAreaLst(GameAreaEnum.getAll());

		// 2加载服务器，与大区联动
		bo.setGameServerLst(GameServerEnum.getAll());

		// 3.加载阵营
		bo.setGameCampLst(GameCampEnum.getAll());

		// 4.加载门派
		bo.setGameSectLst(GameSectEnum.getAll());

		// 5.加载体型
		bo.setGamebodyTypeLst(GameBodyTypeEnum.getAll());

		// 6.加载装备
		bo.setGameEquipmentLst(GameEquipmentEnum.getAll());

		// 7.加载账号亮点
		bo.setGameAccountHighlightsLst(GameAccountHighlightsEnum.getAll());

		logger.info("AccountImpl-load-service-return,{}", JSONObject.toJSONString(bo));
	}

	@Override
	public void add(AccountBo bo) {

		logger.info("AccountImpl-add-service-in,{}", JSONObject.toJSONString(bo));

		// 1.业务逻辑校验
		bizVerify(bo);

		// 2添加账号，由于前台传过来的都是String,我们需要将其转为数据库对应的格式
		Product product = new Product();
		BeanUtils.copyProperties(bo, product);
		product.setGameArea(GameAreaEnum.getByDistCode(bo.getGameArea()).getCode());
		product.setGameBodyType(GameBodyTypeEnum.getByDistCode(bo.getGameBodyType()).getCode());
		product.setGameCamp(GameCampEnum.getByDistCode(bo.getGameCamp()).getCode());
		product.setGameSect(GameSectEnum.getByDistCode(bo.getGameSect()).getCode());
		product.setGameServer(GameServerEnum.getByDistCode(bo.getGameServer()).getCode());
		product.setAllowCw(Integer.parseInt(bo.getAllowCw()));
		product.setAllowJJC(Integer.parseInt(bo.getAllowJJC()));
		// 如果允许JCC
		if (CommonConstant.STRING_ONE.equals(bo.getAllowJJC())) {
			product.setJJC22Code(new BigDecimal(bo.getJJC_22_code()));
			product.setJJC33Code(new BigDecimal(bo.getJJC_33_code()));
			product.setJJC55Code(new BigDecimal(bo.getJJC_55_code()));
		}
		// 账号亮点
		for (String appearance : bo.getAppearance()) {
			GameAccountHighlightsEnum appearanceItem = GameAccountHighlightsEnum.getByDistCode(appearance);
			if (appearanceItem != null) {
				product.setAppearance(appearanceItem.getCode() + CommonConstant.DIVIDE);
			}
		}
		for (String clock : bo.getCloak()) {
			GameAccountHighlightsEnum cloakItem = GameAccountHighlightsEnum.getByDistCode(clock);
			if (cloakItem != null) {
				product.setCloak(cloakItem.getCode() + CommonConstant.DIVIDE);
			}
		}
		for (String goodenHair : bo.getGoodenHair()) {
			GameAccountHighlightsEnum goodenHairItem = GameAccountHighlightsEnum.getByDistCode(goodenHair);
			if (goodenHairItem != null) {
				product.setGoodenHair(goodenHairItem.getCode() + CommonConstant.DIVIDE);
			}
		}
		for (String redHair : bo.getRedHair()) {
			GameAccountHighlightsEnum redHairItem = GameAccountHighlightsEnum.getByDistCode(redHair);
			if (redHairItem != null) {
				product.setRedHair(redHairItem.getCode() + CommonConstant.DIVIDE);
			}
		}

		if (bo.getRentHour() != null) {
			product.setRentHour(new BigDecimal(bo.getRentHour()));
		}
		if (bo.getRentDay() != null) {
			product.setRentDay(new BigDecimal(bo.getRentDay()));
		}
		if (bo.getRentMonth() != null) {
			product.setRentMonth(new BigDecimal(bo.getRentMonth()));
		}
		// 记录状态，初始化为有效
		product.setState(true);
		product.setCheckState(CommonConstant.INTEGER_ONE);

		// 3.存储
		productDao.save(product);

		logger.info("AccountImpl-add-service-return,{}", JSONObject.toJSONString(bo));

	}

	private void bizVerify(AccountBo bo) {
		// TODO Auto-generated method stub
		if (CommonConstant.STRING_ONE.equals(bo.getAllowJJC())) {
			if (!StringUtils.hasText(bo.getJJC_22_code())) {
				throw new BizException("", " 当允许JJC时JJC_22_code不能为空");
			}
			if (!StringUtils.hasText(bo.getJJC_33_code())) {
				throw new BizException("", " 当允许JJC时JJC_33_code不能为空");
			}
			if (!StringUtils.hasText(bo.getJJC_55_code())) {
				throw new BizException("", " 当允许JJC时JJC_55_code不能为空");
			}
		}

	}

	@Override
	@Transactional
	public void addPicture(AccountBo bo) {

		// 1.在Product表中查找记录
		Product product = productDao.findById(new Integer(bo.getProductId()))
				.orElseThrow(() -> new BizException(RespToAppEnum.USER_NOT_FOUND));

		// 2.插入服务器
		// 获取文件名
		String fileName = bo.getFile().getOriginalFilename();
		logger.info("上传的文件名为：" + fileName);
		// 获取文件的后缀名
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
		logger.info("上传的后缀名为：" + suffixName);
		// 文件上传后的路径,服务器+角色名为文件夹名称
		fileName = product.getGameServer() + "$" + product.getGameRoleName() + "$" + fileName;
		// 解决中文问题，liunx下中文路径，图片显示问题
		// fileName = UUID.randomUUID() + suffixName;
		File dest = new File(CommonConstant.FILEPATH + fileName);
		// 检测是否存在目录
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}
		try {
			bo.getFile().transferTo(dest);
			logger.info("上传成功后的文件路径为：" + CommonConstant.FILEPATH + fileName);
		} catch (IllegalStateException e) {
			logger.error(RespToAppEnum.FILE_NOT_EXIST.getMessage(), e);
			throw new BizException(RespToAppEnum.FILE_NOT_EXIST);
		} catch (IOException e) {
			logger.error(RespToAppEnum.FILE_READ_OR_WRITE_FAILED.getMessage(), e);
			throw new BizException(RespToAppEnum.FILE_READ_OR_WRITE_FAILED);
		}

		// 3.插入图片资源表
		SysImages image = new SysImages();
		image.setRelationalId(product.getId());
		image.setUrl(CommonConstant.FILEPATH + fileName);
		image.setImagesType(new Integer(bo.getImgType()));
		image.setState(CommonConstant.INTEGER_ONE);
		sysImagesDao.save(image);

		// 封装返回值
		bo.setImgId(image.getId() + "");
		bo.setImgUrl(image.getUrl());
	}

	/**
	 * 只可以修改部分字段
	 */
	@Override
	public void update(AccountBo bo) {
		logger.info("AccountImpl-add-service-in,{}", JSONObject.toJSONString(bo));

		// 1.业务逻辑校验
		bizVerify(bo);

		// 2添加账号，由于前台传过来的都是String,我们需要将其转为数据库对应的格式
		Product product = new Product();
		BeanUtils.copyProperties(bo, product);
		product.setGameArea(GameAreaEnum.getByDistCode(bo.getGameArea()).getCode());
		product.setGameBodyType(GameBodyTypeEnum.getByDistCode(bo.getGameBodyType()).getCode());
		product.setGameCamp(GameCampEnum.getByDistCode(bo.getGameCamp()).getCode());
		product.setGameSect(GameSectEnum.getByDistCode(bo.getGameSect()).getCode());
		product.setGameServer(GameServerEnum.getByDistCode(bo.getGameServer()).getCode());
		product.setAllowCw(Integer.parseInt(bo.getAllowCw()));
		product.setAllowJJC(Integer.parseInt(bo.getAllowJJC()));
		// 如果允许JCC
		if (CommonConstant.STRING_ONE.equals(bo.getAllowJJC())) {
			product.setJJC22Code(new BigDecimal(bo.getJJC_22_code()));
			product.setJJC33Code(new BigDecimal(bo.getJJC_33_code()));
			product.setJJC55Code(new BigDecimal(bo.getJJC_55_code()));
		}
		// 账号亮点
		for (String appearance : bo.getAppearance()) {
			GameAccountHighlightsEnum appearanceItem = GameAccountHighlightsEnum.getByDistCode(appearance);
			if (appearanceItem != null) {
				product.setAppearance(appearanceItem.getCode() + CommonConstant.DIVIDE);
			}
		}
		for (String clock : bo.getCloak()) {
			GameAccountHighlightsEnum cloakItem = GameAccountHighlightsEnum.getByDistCode(clock);
			if (cloakItem != null) {
				product.setCloak(cloakItem.getCode() + CommonConstant.DIVIDE);
			}
		}
		for (String goodenHair : bo.getGoodenHair()) {
			GameAccountHighlightsEnum goodenHairItem = GameAccountHighlightsEnum.getByDistCode(goodenHair);
			if (goodenHairItem != null) {
				product.setGoodenHair(goodenHairItem.getCode() + CommonConstant.DIVIDE);
			}
		}
		for (String redHair : bo.getRedHair()) {
			GameAccountHighlightsEnum redHairItem = GameAccountHighlightsEnum.getByDistCode(redHair);
			if (redHairItem != null) {
				product.setRedHair(redHairItem.getCode() + CommonConstant.DIVIDE);
			}
		}
		if (bo.getRentHour() != null) {
			product.setRentHour(new BigDecimal(bo.getRentHour()));
		}
		if (bo.getRentDay() != null) {
			product.setRentDay(new BigDecimal(bo.getRentDay()));
		}
		if (bo.getRentMonth() != null) {
			product.setRentMonth(new BigDecimal(bo.getRentMonth()));
		}
		// 记录状态，初始化为有效
		product.setState(true);
		product.setCheckState(CommonConstant.INTEGER_ONE);

		// 3.存储
		productDao.save(product);

		logger.info("AccountImpl-add-service-return,{}", JSONObject.toJSONString(bo));

	}

	@Override
	public void confirm(AccountBo bo) {
		// TODO Auto-generated method stub
		logger.info("AccountImpl-confirm-service-in,{}", JSONObject.toJSONString(bo));

		// 1.先查询是否存在
		Product product = productDao.findById(new Integer(bo.getProductId()))
				.orElseThrow(() -> new BizException(RespToAppEnum.PRODUCTID_NOT_EXIST));

		// 2.更新审核状态
		if (bo.getCheckState() != null) {
			CheckStateEnum checkStateEnum = Optional.ofNullable(CheckStateEnum.getByDistCode(bo.getCheckState()))
					.orElseThrow(() -> new BizException(RespToAppEnum.BADREQUEST.getCode(),
							RespToAppEnum.BADREQUEST.getMessage() + "checkState格式不正确"));

			product.setCheckState(checkStateEnum.getCode());
		}
		if (bo.getState() != null) {
			StateEnum stateEnum = Optional.ofNullable(StateEnum.getByDistCode(bo.getState()))
					.orElseThrow(() -> new BizException(RespToAppEnum.BADREQUEST.getCode(),
							RespToAppEnum.BADREQUEST.getMessage() + "state格式不正确"));

			product.setState(CommonConstant.INTEGER_ONE.equals(stateEnum.getCode()) ? true : false);// 一定非空
		}
		if (bo.getComment() != null) {
			product.setComment(bo.getComment());
		}

		// 3.更新状态
		productDao.save(product);

		// 4.短信提醒可以丢MQ

		logger.info("AccountImpl-confirm-service-return,{}", JSONObject.toJSONString(bo));
	}

}
